package com.atguigu.product.service.impl;

import com.alibaba.druid.util.StringUtils;
import com.atguigu.clients.CategoryClient;
import com.atguigu.clients.SearchClient;
import com.atguigu.param.*;
import com.atguigu.pojo.Picture;
import com.atguigu.pojo.Product;
import com.atguigu.product.mapper.PictureMapper;
import com.atguigu.product.mapper.ProductMapper;
import com.atguigu.product.service.ProductService;
import com.atguigu.utils.R;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;


@Service
@Slf4j
public class ProductServiceImpl extends ServiceImpl<ProductMapper,Product> implements ProductService {

    @Autowired
    private SearchClient searchClient;

    @Autowired
    ProductMapper productMapper;

    @Autowired
    PictureMapper pictureMapper;


    //导入客户端
    @Autowired
    CategoryClient categoryClient;

    // value = "list.product"代表缓存组件的名字

    @Cacheable(value = "list.product",key = "#categoryName")
    @Override
    public R promo(String categoryName) {

        R r = categoryClient.detail(categoryName);
        if(r.getCode().equals(R.FAIL_CODE)){//失败
            return r;
        }

        // 微服务调用，json传输
//        Category category = (Category) r.getData();
        LinkedHashMap<String,Object> map = (LinkedHashMap<String, Object>) r.getData();
        Integer categoryId = (Integer) map.get("category_id");

        QueryWrapper<Product> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("category_id",categoryId);
        queryWrapper.orderByDesc("product_sales");

        Page<Product> page = new Page<>(1,7);
        //复用page
        page = productMapper.selectPage(page, queryWrapper);

        List<Product> records = page.getRecords();//获取数据
        long total = page.getTotal();//获取数据总条数

        return R.ok("查询成功",records);

    }

    @Cacheable(value = "list.product",key = "#productHotsParam.categoryName")
    @Override
    public R hots(ProductHotsParam productHotsParam) {

        //微服务调用
        R r = categoryClient.names(productHotsParam);
        if(r.getCode().equals(R.FAIL_CODE)){
            return r;
        }

        List<Object> ids = (List<Object>) r.getData();
        QueryWrapper<Product> queryWrapper = new QueryWrapper<>();
        queryWrapper.in("category_id",ids);
        queryWrapper.orderByDesc("product_sales");
        Page<Product> page = new Page<Product>(1,7);
        page = productMapper.selectPage(page, queryWrapper);

        List<Product> records = page.getRecords();
        return R.ok("查询成功",records);
    }

    @Cacheable(value = "list.category",key = "#root.methodName")
    @Override
    public R categoryList() {

        R r = categoryClient.list();
        return r;
    }

    @Cacheable(value = "list.product",key = "#productBycategoryParam.categoryID" +
            "+'-'+#productBycategoryParam.currentPage+'-'+#productBycategoryParam.pageSize")
    @Override
    public R bycategory(ProductBycategoryParam productBycategoryParam) {

        List<Integer> categoryIDs = productBycategoryParam.getCategoryID();
        QueryWrapper<Product> queryWrapper = new QueryWrapper<>();
        if(categoryIDs.size()>0){
            queryWrapper.in("category_id",categoryIDs);
        }

        Page<Product> page = new Page<>(productBycategoryParam.getCurrentPage(),productBycategoryParam.getPageSize());
        page = productMapper.selectPage(page, queryWrapper);

        return R.ok("查询成功",page.getRecords(),page.getTotal());
    }

    @Cacheable(value = "product",key = "#productID")
    @Override
    public R detail(Integer productID) {

        Product product = productMapper.selectById(productID);
        return R.ok("查询成功",product);

    }

    @Cacheable(value = "picture",key = "#productID")
    @Override
    public R pictures(Integer productID) {

        QueryWrapper<Picture> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("product_id",productID);

        List<Picture> pictures = pictureMapper.selectList(queryWrapper);
        return R.ok("查询成功",pictures);
    }

    @Override
    public List<Product> list() {

        return productMapper.selectList(null);
    }

    @Override
    public R search(ProductSearchParam productSearchParam) {

        return searchClient.product(productSearchParam);
    }

    @Override
    public R ids(ProductIdsParam productIdsParam) {

        QueryWrapper<Product> queryWrapper = new QueryWrapper<>();
        queryWrapper.in("product_id",productIdsParam.getProductIds());
        List<Product> products = productMapper.selectList(queryWrapper);
        return R.ok("收藏列表查询成功",products);
    }

    @Override
    public Product id(Integer productId) {

        return productMapper.selectById(productId);
    }

    @Override
    public void batchNumber(List<ProductNumberParam> productNumberParams) {

        // 批量操作
        Map<Integer, ProductNumberParam> map = productNumberParams.stream().collect(Collectors.toMap(ProductNumberParam::getProductId, v -> v));
        Set<Integer> productIds = map.keySet();
        List<Product> products = productMapper.selectBatchIds(productIds);
        for (Product product : products) {
            product.setProductNum(product.getProductNum()-
                    map.get(product.getProductId()).getProductNum());
            product.setProductSales(product.getProductSales()+
                    map.get(product.getProductId()).getProductNum());
        }
        this.updateBatchById(products);
    }

    @Override
    public Long count(Integer categoryId) {

        QueryWrapper<Product> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("category_id",categoryId);
        Long num = productMapper.selectCount(queryWrapper);
        return num;
    }

    @Transactional
    @Override
    public R save(ProductSaveParam productSaveParam) {

        // 更新mysql库
        Product product = new Product();
        BeanUtils.copyProperties(productSaveParam,product);
        int i = productMapper.insert(product);

        String pictures = productSaveParam.getPictures();
        if(!StringUtils.isEmpty(pictures)){
            //特殊符号来讲只需要加[]、或是\\即可
            String[] pics = pictures.split("\\+");
            for (String pic : pics) {
                Picture picture = new Picture();
                picture.setIntro(null);
                picture.setProductId(product.getProductId());
                picture.setProductPicture(pic);
                pictureMapper.insert(picture);
            }
        }

        // 同步更新es库，不能用mq异步,因为要立即展现，可能来不及更新es库
        return searchClient.save(product);
    }

    @Override
    public R update(Product product) {

        productMapper.updateById(product);

        //同步更新es库
        return searchClient.save(product);
    }

    @Override
    public R remove(Integer productId) {

        productMapper.deleteById(productId);

        //同步删除es库
        return searchClient.remove(productId);
    }


}
